﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Extension {
  public static class DictionaryExt {
    /// <summary>
    /// 尝试将键和值添加到字典中：如果不存在，添加，存在，则什么都不做
    /// </summary>
    /// <typeparam name="TKey">键类型</typeparam>
    /// <typeparam name="TValue">值类型</typeparam>
    /// <param name="dic"></param>
    /// <param name="key">键</param>
    /// <param name="value">值</param>
    /// <returns></returns>
    public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key,
      TValue value) {
      if (!dic.ContainsKey(key)) dic.Add(key, value);
      return dic;
    }

    /// <summary>
    /// 将键和值添加到字典中，如果键已存在，则替换原有键的值
    /// </summary>
    /// <typeparam name="TKey">键的类型</typeparam>
    /// <typeparam name="TValue">值的类型</typeparam>
    /// <param name="dic"></param>
    /// <param name="key">键</param>
    /// <param name="value">值</param>
    /// <returns></returns>
    public static Dictionary<TKey, TValue> AddOrReplace<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key,
      TValue value) {
      dic[key] = value;
      return dic;
    }

    /// <summary>
    /// 获取字典中指定键的值，不存在，则默认返回该类型的默认值
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="dic"></param>
    /// <param name="key"></param>
    /// <param name="defaultValue"></param>
    /// <returns></returns>
    public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key,
      TValue defaultValue = default(TValue)) {
      return dic.ContainsKey(key) ? dic[key] : defaultValue;
    }

    /// <summary>
    /// 向字典中批量添加元素
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    /// <param name="dic"></param>
    /// <param name="values"></param>
    /// <param name="replaceExisted">是否替换已存在的元素，默认为否</param>
    /// <returns></returns>
    public static Dictionary<TKey,TValue> AddRange<TKey,TValue>(this Dictionary<TKey,TValue> dic,IEnumerable<KeyValuePair<TKey,TValue>> values, bool replaceExisted = false) {
      foreach (var value in values) {
        if (!dic.ContainsKey(value.Key) || replaceExisted) dic[value.Key] = value.Value;
      }
      return dic;
    }
  }
}
